package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetMealServiceImpl implements SetmealService {
    @Autowired
    private FreeMarkerConfigurer freemarkerConfig;
    @Autowired
    private SetmealDao setMealDao;
    @Autowired
    private JedisPool jedisPool;
    @Value("${out_put_path}")//从属性文件读取输出目录的路径
    private String outputpath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkGroupIds) {
        setMealDao.add(setmeal);
        if (checkGroupIds.length != 0 && checkGroupIds != null) {
            for (Integer id : checkGroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmeal_id", setmeal.getId());
                map.put("checkgroup_id", id);
                setMealDao.setSetmealAndCheckGroup(map);
            }
        }
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        if (queryPageBean.getQueryString() != null && queryPageBean.getQueryString().length() != 0) {
            PageHelper.startPage(1, 10);
        } else {
            PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        }
        Page<Setmeal> page = setMealDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public Setmeal findById(Integer id) {
        return setMealDao.findById(id);
    }


    @Override
    public List<Integer> findCheckgroupIdsBySetMealId(Integer id) {
        return setMealDao.findCheckgroupIdsBySetMealId(id);
    }

    @Override
    public List<Setmeal> findAllSetmeal() {
        return setMealDao.findAllSetmeal();
    }

    @Override
    public Setmeal findAllById(Integer id) {
        return setMealDao.findAllById(id);
    }

    @Override
    public void delete(Integer id) {
        //删中间表
        setMealDao.deleteCheckGroupIdsBySetmealId(id);
        setMealDao.deleteSetmeal(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] ids) {
        //将原先中间表关系删除.添加新的关系,修改setmeal表数据
        setMealDao.deleteByCondition(setmeal.getId());
        if (ids.length != 0 && ids != null) {
            for (Integer id : ids) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmeal_id", setmeal.getId());
                map.put("checkgroup_id", id);
                setMealDao.setSetmealAndCheckGroup(map);
            }
            setMealDao.edit(setmeal);
        }
    }

    //生成静态页面
    public void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.findAllSetmeal();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成套餐详情静态页面
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("setmeal",  this.findAllById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl",
                    "setmeal_detail_"+setmeal.getId()+".html",
                    dataMap);
        }
    }
    //生成套餐列表静态页面
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",dataMap);
    }

    public void generateHtml(String templateName,String htmlPageName,Map<String, Object> dataMap){
        Configuration configuration = freemarkerConfig.getConfiguration();
        Writer out = null;
        try {
            //加载模板文件
            Template template = configuration.getTemplate(templateName);
            //生成数据
            File docFile = new File(outputpath+"/"+htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            //输出文件
            template.process(dataMap,out);
        }catch (Exception e ){
            e.printStackTrace();
        }finally {
            try{
                if (null!=out){
                    out.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
